<?php
declare (strict_types=1);

namespace app\school\validate\school\admin;

use app\admin\logic\system\Config as SystemConfig;
use app\school\model\school\admin\SchoolLevel as SchoolLevelModel;
use think\Validate;

/**
 * 机构等级验证
 */
class SchoolLevel extends Validate
{
    /**
     * 定义验证规则
     * 格式：'字段名'    =>    ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'id'              => 'require',
        'title'           => 'require',
        'min_sales_price' => 'require|egt:0|checkPrice',
        'proportion'      => 'require|egt:0|checkMax',

    ];

    /**
     * 定义错误信息
     * 格式：'字段名.规则名'    =>    '错误信息'
     *
     * @var array
     */
    protected $message = [
        'id'              => '操作出错',
        'title'           => '等级名称必须填写',
        'min_sales_price' => '最小销售额必须大于等于0',
        'proportion.egt'  => '分成比例必须大于等于0',
    ];

    /**
     * 验证场景
     */
    protected $scene = [
        'create' => ['title', 'min_sales_price', 'proportion'],
        'edit'   => ['id', 'title', 'min_sales_price', 'proportion'],
    ];

    /**
     * 检测配置的金额
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-22
     * @param    [type]                         $value [description]
     */
    protected function checkPrice($value, $rule, $data)
    {
        // 是否编辑
        if ($this->currentScene == 'edit') {
            $builder = app(SchoolLevelModel::class)->where('id', '<>', $data['id'])->where('min_sales_price', '=', $value);
        } else {
            $builder = app(SchoolLevelModel::class)->where('min_sales_price', '=', $value);
        }

        $has = $builder->find();
        if ($has) {
            return '已存在相同销售额的等级';
        }

        return true;
    }

    /**
     * 检测配置的分成比例
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-22
     */
    protected function checkMax($value, $rule, $data)
    {
        $key    = 'split.config';
        $config = SystemConfig::get($key);
        $max    = $config['platform'] + $config['school'];

        if ($max < $value) {
            return '分成比例不能超过平台与机构比例之和';
        }

        return true;
    }
}
